package beautiful.butterfly.drds.binlog.netty.server;


import beautiful.butterfly.drds.binlog.connection.Connection;
import beautiful.butterfly.drds.binlog.utils.PropertiesExtend;
import beautiful.butterfly.drds.binlog.utils.TimeUtils;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

@Slf4j
public class NettyQueue
{
    // poll: 若队列为空，返回null。
    // remove:若队列为空，抛出NoSuchElementException异常。
    // take:若队列为空，发生阻塞，等待有元素。

    // put---无空间会等待
    // add--- 满时,立即返回,会抛出异常
    // offer---满时,立即返回,不抛异常


    public static BlockingQueue<Connection> objectQueue = new LinkedBlockingQueue<Connection>();

    public static void addObject(Connection obj)
    {
        objectQueue.offer(obj);
        new Thread(new Runnable()
        {// 启动一个线程去触发...
            @Override
            public void run()
            {
                // TODO Auto-generated method stub
                PropertiesExtend p = PropertiesExtend.getInstance();
                if (null != p)
                {// 连接本机的netty服务器
                    String ip = "127.0.0.1";
                    int port = p.getNettyPort();
                    if (null != ip && port >= 0)
                    {
                        Socket socket = null;
                        try
                        {
                            socket = new Socket();
                            log.info("try to connect ip: " + ip + " port:" + port);
                            socket.connect(new InetSocketAddress(ip, port), 0);// 还是给一个连接超时16秒
                            TimeUtils.sleepSeconds(6);// 睡眠6秒再退出,足够的时间给netty处理连接了
                        } catch (Exception e)
                        {
                            log.info(e.toString());
                        } finally
                        {
                            if (null != socket)
                            {// 主动关闭连接
                                try
                                {
                                    socket.close();
                                } catch (IOException e)
                                {
                                }
                            }
                        } // try...catch...finally结束
                    } // if结束
                }
            }
        }).start();

    }

    ;

    public static Connection getObject()
    {
        return objectQueue.poll();
    }

}